import { getCookieItem, setCookieItem } from '../../../utils/cookie'
import COOKIE_KEY from '../../../config/cookie'
/**
       * 创建钉钉登录二维码
       * @author Enzo
       * @date 2020-7-1
       */
export function createCode (a, url) {
  const c = document.createElement('iframe')
  let d = url + a.goto
  d += a.style ? '&style=' + encodeURIComponent(a.style) : ''
  d += a.href ? '&href=' + a.href : ''
  c.src = d
  c.frameBorder = '0'
  c.allowTransparency = 'true'
  c.scrolling = 'no'
  c.width = a.width ? a.width + 'px' : '364px'
  c.height = a.height ? a.height + 'px' : '400px'
  const box = document.getElementById(a.id)
  box.innerHTML = ''
  box.appendChild(c)
}
/**
 * 打开,显示钉钉扫码登录
 * @author Enzo
 * @date 2020-7-1
 */
function openDingTalkQrCode (state, callBackUrl = 'http://dcwbs.dongcheng999.com:9032/#/dingTalkAuthentication', appId = 'dingoaroxknznsrqtv9pnt') {
  const url = encodeURIComponent(callBackUrl)
  const goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + appId +
          '&response_type=code&scope=snsapi_login&state=' + state + '&redirect_uri=' + url)
  const DingUrl = 'https://login.dingtalk.com/login/qrcode.htm?goto='
  // if (state === 'DingTalkLogion') {
  createCode({
    id: 'login_container',
    goto: goto,
    style: 'border:none;background-color:#FFFFFF;',
    width: '360',
    height: '290'
  }, DingUrl)
  // 启用监听
  listenerDingTalkQrCode(state)
  // } else {}
}
export { openDingTalkQrCode }
/**
 * 监听钉钉二维码扫码，扫码后，跳转到回调页面
 * @author Enzo
 * @date 2020-7-1
 */
export function listenerDingTalkQrCode (state) {
  const handleMessage = function (event) {
    const origin = event.origin
    if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
      // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
      // console.log('loginTmpCode', loginTmpCode)
      const loginTmpCode = event.data
      window.location.href = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?state=' + state + '&loginTmpCode=' + loginTmpCode
    }
  }
  if (typeof window.addEventListener !== 'undefined') {
    window.addEventListener('message', handleMessage, false)
  } else if (typeof window.attachEvent !== 'undefined') {
    window.attachEvent('onmessage', handleMessage)
  }
}
/**
 * 创建qq登录二维码
 * @author kzj
 * @date 2020-7-10
 */
export function openQQ () {
  // 应用的appid
  var appId = '10150967905'
  // 登录授权后的回调地址，设置为当前URL
  var redirectURI = encodeURIComponent('http://dcwbs.dongcheng999.com:9032/#/dingTalkAuthentication')
  // 初始构造请求
  if (window.location.hash.length === 0) {
    const path = 'https://graph.qq.com/oauth2.0/authorize?'
    const queryParams = ['client_id=' + appId,
      'redirect_uri=' + redirectURI,
      'scope=' + 'get_user_info,list_album,upload_pic,add_feeds,do_like', 'response_type=token']
    const query = queryParams.join('&')
    const url = path + query
    window.location.href = url
  } else {
    // 在成功授权后回调时location.hash将带有access_token信息，开始获取openid
    // 获取access token
    const accessToken = window.location.hash.substring(1)
    const map = toParamMap(accessToken)
    // 记录access token

    setCookieItem(COOKIE_KEY.accessToken, map.access_token)
    // 使用access Token来获取用户的openId
    const path = 'https://graph.qq.com/oauth2.0/me?'
    const queryParams = ['access_token=' + '1231231313', 'callback=callback']
    const query = queryParams.join('&')
    const url = path + query
    openImplict(url)
  }
}

/**
 * 切割字符串转换参数表
 */
export function toParamMap (str) {
  var map = {}
  var segs = str.split('&')
  for (var i in segs) {
    var seg = segs[i]
    var idx = seg.indexOf('=')
    if (idx < 0) {
      continue
    }
    var name = seg.substring(0, idx)
    var value = seg.substring(idx + 1)
    map[name] = value
  }
  return map
}
// 隐式获取url响应内容(JSONP)
export function openImplict (url) {
  var script = document.createElement('script')
  script.src = url
  document.body.appendChild(script)
}
// 获得openid的回调
export function callback (obj) {
  var openid = obj.openid
  // 跳转服务端登录url
  var resulturl = '@{openapi.QQs.login_result()}'
  const accessToken = getCookieItem(COOKIE_KEY.accessToken)
  // 向服务端传输access_token及openid参数
  document.location.href = resulturl + '?access_token=' + accessToken + '&openid=' + openid
}
/**
 * 创建微信登录二维码
 * @author kzj
 * @date 2020-7-14
 */
export function createWechatCode (a) {
  var c = 'default'
  a.self_redirect === !0 ? c = 'true' : a.self_redirect === !1 && (c = 'false')
  var d = document.createElement('iframe')
  var e = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + a.appid + '&scope=' + a.scope + '&redirect_uri=' + a.redirect_uri + '&state=' + a.state + '&login_type=jssdk&self_redirect=' + c + '&styletype=' + (a.styletype || '') + '&sizetype=' + (a.sizetype || '') + '&bgcolor=' + (a.bgcolor || '') + '&rst=' + (a.rst || '')
  e += a.style ? '&style=' + a.style : ''
  e += a.href ? '&href=' + a.href : ''
  d.src = e
  d.frameBorder = '0'
  d.allowTransparency = 'true'
  d.scrolling = 'no'
  d.width = '300px'
  d.height = '380px'
  var f = document.getElementById(a.id)
  f.innerHTML = ''
  f.appendChild(d)
}

/**
 * 打开,显示微信扫码登录
 * @author kzj
 * @date 2020-7-14
 */
export function weChatLogin (state, appid, redirectUri) {
  createWechatCode({
    self_redirect: false,
    id: 'WechatLogin_container',
    appid: appid,
    scope: 'snsapi_login',
    redirect_uri: redirectUri,
    state: state,
    style: 'black'
  })
}
